﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Runtime.InteropServices;

namespace Connect
{
    /// <summary>
    /// Thay đổi địa chỉ IP máy tính
    /// </summary>
    public partial class ChangeIP : Form
    {
        public ChangeIP()
        {
            InitializeComponent();
        }

        #region Thao tác giao diện
        private void ma_CheckedChanged(object sender, EventArgs e)
        {
            ipgroup.Enabled = (ma.Checked == true) ? true : false;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }
       public int DemDauCham(string ip)
        {
            int dem = 0;
            for (int i = 0; i < ip.Length; i++)
            {
                if (ip.Substring(i,1)==".")
                {
                    dem++;
                }
            }
            return dem;
        }
       void DieuKhien()
       {
           if ((txtIP.ForeColor == Color.Blue) && (txtSubnet.ForeColor == Color.Blue) && (txtGateway.ForeColor == Color.Blue) && (txtDNS.ForeColor == Color.Blue) && (txtADNS.ForeColor == Color.Blue))
           {
               btnActivate.Enabled = true;
           }
           else
           {
                btnActivate.Enabled = false;
           }
       }

        static public uint  OctetDau(string ipAddress)
            {
                System.Net.IPAddress iPAddress = System.Net.IPAddress.Parse(ipAddress);
                byte[] byteIP = iPAddress.GetAddressBytes();
                uint ipInUint = (uint)byteIP[0];     
                return ipInUint;
             }
        static public string SubnetTuDong(String ipaddress)
      {
        uint firstOctet =  OctetDau(ipaddress);
         if (firstOctet >= 0 && firstOctet <= 127)
             return "255.0.0.0";
         else if (firstOctet >= 128 && firstOctet <= 191)
             return "255.255.0.0";
         else if (firstOctet >= 192 && firstOctet <= 223)
             return "255.255.255.0";
       else return "0.0.0.0";
      }

        
        private void txtIP_Leave(object sender, EventArgs e)
        {
            _CurrentNICProfile.IP = txtIP.Text;
            if (DemDauCham(txtIP.Text.Trim()) == 3)
            {
                txtIP.BackColor = Color.White;
                txtIP.ForeColor = Color.Blue;
                txtSubnet.Text = SubnetTuDong(txtIP.Text.Trim());
            }
            else
            {
                txtIP.BackColor = Color.Red;
                txtIP.ForeColor = Color.White;
            }
            DieuKhien();
        }

        private void txtSubnet_Leave(object sender, EventArgs e)
        {
            _CurrentNICProfile.Subnet = txtSubnet.Text;
            if (DemDauCham(txtSubnet.Text.Trim()) == 3)
            {
                txtSubnet.BackColor = Color.White;
                txtSubnet.ForeColor = Color.Blue;
            }
            else
            {
                txtSubnet.BackColor = Color.Red;
                txtSubnet.ForeColor = Color.White;
            }
            DieuKhien();
        }

        private void txtGateway_Leave(object sender, EventArgs e)
        {
            _CurrentNICProfile.Gateway = txtGateway.Text;
            if (DemDauCham(txtGateway.Text.Trim()) == 3)
            {
                txtGateway.BackColor = Color.White;
                txtGateway.ForeColor = Color.Blue;
            }
            else
            {
                txtGateway.BackColor = Color.Red;
                txtGateway.ForeColor = Color.White;
            }
            DieuKhien();
        }

        public string DNS = "";
        private void txtDNS_Leave(object sender, EventArgs e)
        {
            if (DemDauCham(txtDNS.Text.Trim()) == 3)
            {
                txtDNS.BackColor = Color.White;
                txtDNS.ForeColor = Color.Blue;
            }
            else
            {
                txtDNS.BackColor = Color.Red;
                txtDNS.ForeColor = Color.White;
            }
            DieuKhien();
        }

        private void txtADNS_Leave(object sender, EventArgs e)
        {
            if (DemDauCham(txtADNS.Text.Trim()) == 3)
            {
                txtADNS.BackColor = Color.White;
                txtADNS.ForeColor = Color.Blue;
            }
            else
            {
                txtADNS.BackColor = Color.Red;
                txtADNS.ForeColor = Color.White;
            }
  DieuKhien();
        }        
        #endregion

        #region Di chuyển
        private bool drragging;
        private Point pointclicked;
        private void panel1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                drragging = true;
                pointclicked = new Point(e.X, e.Y);
            }
            else
            {
                drragging = false;
            }
        }

        private void panel1_MouseUp(object sender, MouseEventArgs e)
        {
            drragging = false;
        }

        private void panel1_MouseMove(object sender, MouseEventArgs e)
        {
            if (drragging)
            {
                Point pointmoveto = default(Point);
                pointmoveto = this.PointToScreen(new Point(e.X, e.Y));
                pointmoveto.Offset(-pointclicked.X, -pointclicked.Y);
                this.Location = pointmoveto;
            }
        }
        #endregion

        #region Private Variables and properties

        // stores all the profiles
        private ArrayList _Profiles = new ArrayList();

        /// <summary>
        /// Returns the currently selected profile object
        /// </summary>
        private Profile _CurrentProfile
        {
            get
            {
                // find the profile for the currently selected profile
                foreach (Profile profile in _Profiles)
                    if (profile.Name.Equals(_ProfileName))
                        return profile;

                return null;
            }
        }

        /// <summary>
        /// Returns the NICProfile object for the currently selected NIC Name
        /// </summary>
        private NICProfile _CurrentNICProfile
        {
            get
            {
                try
                {
                    // find the NIC Profile for the currently selected NIC name
                    foreach (NICProfile profile in _CurrentProfile.NICProfiles)
                        if (profile.Name.Equals(_NICName))
                            return profile;

                    // not found, create a new NIC Profile
                    NICProfile newProfile = new NICProfile(cboNIC.Text);
                    _CurrentProfile.NICProfiles.Add(newProfile);

                    return newProfile;
                }
                catch (Exception)
                {
                    // create a new profile object
                    Profile newProfile = new Profile("");
                    _Profiles.Add(newProfile);

                    // load the NIC list
                    loadNICs();
                    return null;

                }

            }
        }

        /// <summary>
        /// Returns the current NICName
        /// </summary>
        private string _NICName
        {
            get
            {
                return cboNIC.SelectedItem as string;
            }
        }

        /// <summary>
        /// returns the current profile name
        /// </summary>
        private string _ProfileName
        {
            get
            {
                return "";
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Load profile from configuration file
        /// </summary>
        private void loadProfiles()
        {
            _Profiles = ConfigurationHelper.LoadConfig();
        }

        /// <summary>
        /// Load a particular profile
        /// </summary>
        /// <param name="profile"></param>
        private void loadProfile(Profile profile)
        {
            // load the NIC list
            loadNICs();

          

            btnActivate.Enabled = true;
        }

        /// <summary>
        /// Load NIC names
        /// </summary>
        private void loadNICs()
        {
            // get the NIC names
            ArrayList nicNames = WMIHelper.GetNICNames();

            // populate the NIC list
            cboNIC.Items.Clear();
            foreach (string name in nicNames)
                cboNIC.Items.Add(name);

            // if NIC found, select the first one
            if (cboNIC.Items.Count > 0)
            {
                cboNIC.SelectedIndex = 0;
              
            }
        }


        /// <summary>
        /// Show the IP, DNS, Gateway and Subnet mask for the NIC name
        /// </summary>
        /// <param name="nicName"></param>
        string DNSht = "";
        private void loadNICProfile(string nicName)
        {
            NICProfile nicProfile = _CurrentNICProfile;
            if (null == nicProfile) return;

            txtIP.Text = nicProfile.IP;
            txtSubnet.Text = nicProfile.Subnet;
            txtGateway.Text = nicProfile.Gateway;
            DNSht=nicProfile.DNS;
            try
            {
                txtDNS.Text = DNSht.Substring(0, DNSht.IndexOf(","));
                txtADNS.Text = DNSht.Substring(DNSht.IndexOf(","), DNSht.Length - DNSht.IndexOf(",")).Replace(",", " ").Trim();
            }
            catch (Exception)
            {

                lblCurrentDNS.Text = DNSht;
            }
            if (nicProfile.UseDHCP == true)
            {
                au.Checked = true;
            }
            else
            {
                ma.Checked = true;
            }
        }

      
        private void saveProfiles()
        {
            ConfigurationHelper.SaveConfig(_Profiles);
        }

        private void createNewProfile()
        {
            //	using( NewProfileDialog newProfileDialog = new NewProfileDialog() )
            {

                //if( DialogResult.OK == newProfileDialog.ShowDialog( this ) )
                {
                    // create a new profile object
                    Profile newProfile = new Profile("");
                    _Profiles.Add(newProfile);

                    // load the NIC list
                    loadNICs();
                }
            }
        }

        /// <summary>
        /// Loads current network configuration for the specified NIC and show in 
        /// the current configuration block
        /// </summary>
        /// <param name="nicName"></param>
        private void loadCurrentSetting(string nicName)
        {

            string[] ipAddresses;
            string[] subnets;
            string[] gateways;
            string[] dnses;

            // Load current IP configuration for the selected NIC
            WMIHelper.GetIP(nicName, out ipAddresses, out subnets, out gateways, out dnses);

            // if network connection is disabled, no information will be available
            if (null == ipAddresses || null == subnets || null == gateways || null == dnses)
                return;

            // Show the setting
            lblCurrentIP.Text = string.Join(",", ipAddresses);
            lblCurrentSubnet.Text = string.Join(",", subnets);
            lblCurrentGateway.Text = string.Join(",", gateways);
            DNS = string.Join(",", dnses);
            try
            {
            lblCurrentDNS.Text = DNS.Substring(0,DNS.IndexOf(","));
            lblCurrentADNS.Text = DNS.Substring(DNS.IndexOf(","), DNS.Length - DNS.IndexOf(",")).Replace(",", " ").Trim();        
            }
            catch (Exception)
            {

                lblCurrentDNS.Text = DNS;
            }
           
        }


        /// <summary>
        /// Apply currently selected profile
        /// </summary>
        private void applyProfile()
        {
            ApplyIP applyDialog = new ApplyIP();
            applyDialog.Show();
            applyDialog.Refresh();

            // Start applying setting
            applyDialog.ApplySetting(_CurrentProfile);

            // show current configuration after applying
            loadCurrentSetting(_NICName);
        }

        private void close()
        {
            this.Close();
        }

        private void loadApp()
        {
            loadProfiles();
            loadNICs();
        }

        #endregion

        private void ChangeIP_Load(object sender, EventArgs e)
        {
            loadApp();
        }

        private void ChangeIP_FormClosing(object sender, FormClosingEventArgs e)
        {
            saveProfiles();
        }

        private void cboNIC_SelectedIndexChanged(object sender, EventArgs e)
        {
            loadNICProfile(_NICName);
            loadCurrentSetting(_NICName);
        }

        private void btnActivate_Click(object sender, EventArgs e)
        {
            _CurrentNICProfile.DNS = txtDNS.Text.Trim() + "," + txtADNS.Text.Trim();
            applyProfile();
        }

        private void au_CheckedChanged(object sender, EventArgs e)
        {
            bool allowIP = !au.Checked;
            txtIP.Enabled = txtSubnet.Enabled = txtGateway.Enabled = txtDNS.Enabled = allowIP;
            _CurrentNICProfile.UseDHCP = au.Checked;
        }


    }
}
